﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using Project5188.BUS;
using Project5188.BUS.EducationAndTraining;
using Project5188.BUS.Operations;
using Project5188.BUS.SalesAndCustomerRelations;
using DatePicker = Microsoft.Windows.Controls.DatePicker;
using Image = System.Windows.Controls.Image;

namespace Project5188.Client
{
    /// <summary>
    /// Interaction logic for DetailWindow.xaml
    /// </summary>
    public partial class DetailWindow
    {
        private Dictionary<string, resource> _resourceDic;

        public DetailWindow()
        {
            InitializeComponent();
        }

        public void SetEntity<T>(DetailView<T> detail, string pageName)
        {
            if (detail == null) throw new ArgumentNullException("detail");
            _resourceDic = BUS.Resources.GetResourceByPageName(pageName);

            var propertyInfos = detail.Entity.GetType().GetProperties();
            foreach (var propertyInfo in propertyInfos)
            {
                // ReSharper disable PossibleNullReferenceException
                if (!(propertyInfo.PropertyType).FullName.Contains("Data") &&
                    // ReSharper restore PossibleNullReferenceException
                    !(propertyInfo.PropertyType).FullName.Contains("Project5188") &&
                    propertyInfo.Name != "IsDeleted" &&
                    propertyInfo.Name != "ModifyBy" &&
                    propertyInfo.Name != "ModifyDate" &&
                    propertyInfo.Name != "CreateBy")
                {
                    var value = propertyInfo.GetValue(detail.Entity, null);

                    resource resourceKey;
                    _resourceDic.TryGetValue(propertyInfo.Name, out resourceKey);

                    if (!propertyInfo.Name.Contains("ImagePath"))
                    {
                        var lblHeader = new Label
                                            {
                                                Name = "lbl" + propertyInfo.Name,
                                                Content =
                                                    resourceKey != null
                                                        ? resourceKey.Value + " : "
                                                        : propertyInfo.Name + " : ",
                                                Height = 23,
                                                HorizontalContentAlignment = HorizontalAlignment.Left
                                            };

                        RegisterName(lblHeader.Name, lblHeader);
                        StackPanel1.Children.Add(lblHeader);

                        var lblEmpty = new Label {Height = 10};
                        StackPanel1.Children.Add(lblEmpty);
                    }

                    if (propertyInfo.Name.Contains("ParameterValueID"))
                    {
                        string parameterId = propertyInfo.Name.Split('_')[2];
                        var parameterValues = new ParameterValues();

                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                            // ReSharper restore UseObjectOrCollectionInitializer
                                           {
                                               Name = "drp" + propertyInfo.Name,
                                               SelectedValuePath = "ID",
                                               IsSynchronizedWithCurrentItem = true,
                                               ItemTemplate = Resources["comboTemplate"] as DataTemplate,
                                               Width = 200,
                                               Height = 23,
                                               ItemsSource =
                                                   parameterValues.GetEntityByParameterId(Convert.ToInt64(parameterId)),
                                               HorizontalAlignment = HorizontalAlignment.Right,
                                               IsEditable = false
                                           };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty2 = new Label {Height = 10};
                        StackPanel2.Children.Add(lblEmpty2);
                    }
                    else if ((pageName == Extensions.PageNames.CommunicationInfoPage.ToString() ||
                              pageName == Extensions.PageNames.DinnerExpenseDetailPage.ToString() ||
                              pageName == Extensions.PageNames.DressInfoPage.ToString() ||
                              pageName == Extensions.PageNames.IdCardInfoPage.ToString() ||
                              pageName == Extensions.PageNames.InsuranceInfoPage.ToString() ||
                              pageName == Extensions.PageNames.PersonnelActionPage.ToString() ||
                              pageName == Extensions.PageNames.PersonnelNomineePage.ToString() ||
                              pageName == Extensions.PageNames.PersonnelWorkOutPage.ToString() ||
                              pageName == Extensions.PageNames.PersonnelInspectionPage.ToString()) &&
                             propertyInfo.Name.Split('_').Length > 1 &&
                             propertyInfo.Name.Split('_')[1] == "PersonnelID")
                    {
                        var personelInfos = new PersonnelInfos();
                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                            // ReSharper restore UseObjectOrCollectionInitializer
                                           {
                                               Name = "drp" + propertyInfo.Name,
                                               SelectedValuePath = "a_ID",
                                               IsSynchronizedWithCurrentItem = true,
                                               ItemTemplate = Resources["personnelTemplate"] as DataTemplate,
                                               Width = 200,
                                               Height = 23,
                                               ItemsSource =
                                                   personelInfos.GetEntityList(),
                                               HorizontalAlignment = HorizontalAlignment.Right
                                           };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty6 = new Label {Height = 10};
                        StackPanel2.Children.Add(lblEmpty6);
                    }
                    else if ((pageName == Extensions.PageNames.CustomerSalesInfoPage.ToString() ||
                                pageName == Extensions.PageNames.CreateOfferPage.ToString()) &&
                                propertyInfo.Name.Split('_').Length > 1 &&
                                propertyInfo.Name.Split('_')[1] == "CustomerInfoID")
                    {
                        var customerInfos = new CustomerInfos();
                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                            // ReSharper restore UseObjectOrCollectionInitializer
                                           {
                                               Name = "drp" + propertyInfo.Name,
                                               SelectedValuePath = "a_ID",
                                               IsSynchronizedWithCurrentItem = true,
                                               ItemTemplate = Resources["customerTemplate"] as DataTemplate,
                                               Width = 200,
                                               Height = 23,
                                               ItemsSource =
                                                   customerInfos.GetEntityList(),
                                               HorizontalAlignment = HorizontalAlignment.Right
                                           };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty7 = new Label {Height = 10};
                        StackPanel2.Children.Add(lblEmpty7);
                    }
                    else if ((pageName == Extensions.PageNames.DocumentPage.ToString()) &&
                            propertyInfo.Name.Split('_').Length > 1 &&
                            propertyInfo.Name.Split('_')[1].Contains("UserID"))
                    {
                        var users = new Users();
                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                        // ReSharper restore UseObjectOrCollectionInitializer
                        {
                            Name = "drp" + propertyInfo.Name,
                            SelectedValuePath = "ID",
                            IsSynchronizedWithCurrentItem = true,
                            ItemTemplate = Resources["usersTemplate"] as DataTemplate,
                            Width = 200,
                            Height = 23,
                            ItemsSource =
                                users.GetEntityList(),
                            HorizontalAlignment = HorizontalAlignment.Right
                        };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty14 = new Label { Height = 10 };
                        StackPanel2.Children.Add(lblEmpty14);
                    }
                    else if ((pageName == Extensions.PageNames.InspectionInfoPage.ToString() ||
                        pageName == Extensions.PageNames.InstitutionInspectionPage.ToString()) &&
                    propertyInfo.Name.Split('_').Length > 1 &&
                    propertyInfo.Name.Split('_')[1] == "InstitutionID")
                    {
                        var institutions = new Institutions();
// ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
// ReSharper restore UseObjectOrCollectionInitializer
                        {
                            Name = "drp" + propertyInfo.Name,
                            SelectedValuePath = "a_ID",
                            IsSynchronizedWithCurrentItem = true,
                            ItemTemplate = Resources["institutionTemplate"] as DataTemplate,
                            Width = 200,
                            Height = 23,
                            ItemsSource =
                                institutions.GetEntityList(),
                            HorizontalAlignment = HorizontalAlignment.Right
                        };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty8 = new Label { Height = 10 };
                        StackPanel2.Children.Add(lblEmpty8);
                    }
                    else if ((pageName == Extensions.PageNames.CoursePage.ToString()) && 
                        propertyInfo.Name.Split('_').Length > 1 && 
                        propertyInfo.Name.Split('_')[1] == "TeacherID")
                    {
                        var teacherRegistries = new TeacherRegistries();
                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                        // ReSharper restore UseObjectOrCollectionInitializer
                        {
                            Name = "drp" + propertyInfo.Name,
                            SelectedValuePath = "a_ID",
                            IsSynchronizedWithCurrentItem = true,
                            ItemTemplate = Resources["teacherRegistryTemplate"] as DataTemplate,
                            Width = 200,
                            Height = 23,
                            ItemsSource =
                                teacherRegistries.GetEntityList(),
                            HorizontalAlignment = HorizontalAlignment.Right
                        };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty9 = new Label { Height = 10 };
                        StackPanel2.Children.Add(lblEmpty9);
                    }
                    else if ((pageName == Extensions.PageNames.RollCallPage.ToString() ||
                        pageName == Extensions.PageNames.SuccessStatusPage.ToString()) &&
                        propertyInfo.Name.Split('_').Length > 1 &&
                        propertyInfo.Name.Split('_')[1] == "StudentID")
                    {
                        var studentRegistries = new StudentRegistries();
                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                        // ReSharper restore UseObjectOrCollectionInitializer
                        {
                            Name = "drp" + propertyInfo.Name,
                            SelectedValuePath = "a_ID",
                            IsSynchronizedWithCurrentItem = true,
                            ItemTemplate = Resources["studentRegistryTemplate"] as DataTemplate,
                            Width = 200,
                            Height = 23,
                            ItemsSource =
                                studentRegistries.GetEntityList(),
                            HorizontalAlignment = HorizontalAlignment.Right
                        };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty10 = new Label { Height = 10 };
                        StackPanel2.Children.Add(lblEmpty10);
                    }
                    else if ((pageName == Extensions.PageNames.RollCallPage.ToString()) &&
                    propertyInfo.Name.Split('_').Length > 1 &&
                    propertyInfo.Name.Split('_')[1] == "TimeTableID")
                    {
                        var timeTables = new TimeTables();
                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                        // ReSharper restore UseObjectOrCollectionInitializer
                        {
                            Name = "drp" + propertyInfo.Name,
                            SelectedValuePath = "a_ID",
                            IsSynchronizedWithCurrentItem = true,
                            ItemTemplate = Resources["timeTablesTemplate"] as DataTemplate,
                            Width = 200,
                            Height = 23,
                            ItemsSource =
                                timeTables.GetEntityList(),
                            HorizontalAlignment = HorizontalAlignment.Right
                        };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty11 = new Label { Height = 10 };
                        StackPanel2.Children.Add(lblEmpty11);
                    }
                    else if ((pageName == Extensions.PageNames.SuccessStatusPage.ToString() ||
                        pageName == Extensions.PageNames.TimeTablePage.ToString()) &&
                        propertyInfo.Name.Split('_').Length > 1 &&
                        propertyInfo.Name.Split('_')[1] == "CourseID")
                    {
                        var courses = new Courses();
                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                        // ReSharper restore UseObjectOrCollectionInitializer
                        {
                            Name = "drp" + propertyInfo.Name,
                            SelectedValuePath = "a_ID",
                            IsSynchronizedWithCurrentItem = true,
                            ItemTemplate = Resources["coursesTemplate"] as DataTemplate,
                            Width = 200,
                            Height = 23,
                            ItemsSource =
                                courses.GetEntityList(),
                            HorizontalAlignment = HorizontalAlignment.Right
                        };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty12 = new Label { Height = 10 };
                        StackPanel2.Children.Add(lblEmpty12);
                    }
                    else if ((pageName == Extensions.PageNames.UserPage.ToString()) &&
                        propertyInfo.Name == "RoleGroupID")
                    {
                        var roleGroups = new RoleGroups();
                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                        // ReSharper restore UseObjectOrCollectionInitializer
                        {
                            Name = "drp" + propertyInfo.Name,
                            SelectedValuePath = "ID",
                            IsSynchronizedWithCurrentItem = true,
                            ItemTemplate = Resources["roleGroupsTemplate"] as DataTemplate,
                            Width = 200,
                            Height = 23,
                            ItemsSource =
                                roleGroups.GetEntityList(),
                            HorizontalAlignment = HorizontalAlignment.Right
                        };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty13 = new Label { Height = 10 };
                        StackPanel2.Children.Add(lblEmpty13);
                    }
                    else if (propertyInfo.Name.Split('_').Length > 1 &&
                             propertyInfo.Name.Split('_')[1].StartsWith("Is") ||
                             propertyInfo.Name.StartsWith("Is"))
                    {
                        var chkValue = new CheckBox
                                           {
                                               Name = "chk" + propertyInfo.Name,
                                               HorizontalAlignment = HorizontalAlignment.Right,
                                               Height = 23,
                                               IsChecked = value == null ? false : (bool) value
                                           };

                        RegisterName(chkValue.Name, chkValue);
                        StackPanel2.Children.Add(chkValue);

                        var lblEmpty3 = new Label {Height = 10};
                        StackPanel2.Children.Add(lblEmpty3);
                    }
                    else if (propertyInfo.Name.Contains("Date") && propertyInfo.PropertyType == typeof(DateTime))
                    {
                        var dtValue = new DatePicker
                                          {
                                              Name = "dt" + propertyInfo.Name,
                                              Width = 200,
                                              Height = 23,
                                              HorizontalAlignment = HorizontalAlignment.Right,
                                              SelectedDate =
                                                  ((DateTime) value) != DateTime.MinValue
                                                      ? (DateTime) value
                                                      : (DateTime?) null
                                          };

                        RegisterName(dtValue.Name, dtValue);
                        StackPanel2.Children.Add(dtValue);

                        var lblEmpty4 = new Label {Height = 10};
                        StackPanel2.Children.Add(lblEmpty4);
                    }
                    else if (propertyInfo.Name.Split('_').Length > 1 &&
                             propertyInfo.Name.Split('_')[1].Contains("ImagePath"))
                    {
                        var buffer = (byte[]) value;
                        var stream1 = new MemoryStream(buffer);
                        var image = System.Drawing.Image.FromStream(stream1);

                        var bmp = new Bitmap(image);
                        var hBitmap = bmp.GetHbitmap();
                        System.Windows.Media.ImageSource imageSource =
                            System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero,
                                                                                         Int32Rect.Empty,
                                                                                         BitmapSizeOptions.
                                                                                             FromEmptyOptions());

                        var img = new Image
                                      {
                                          Name = "imgPersonnel",
                                          Source = imageSource,
                                          HorizontalAlignment = HorizontalAlignment.Left,
                                          Width = image.Width,
                                          Height = image.Height
                                      };

                        RegisterName(img.Name, img);
                        StackPanelImage.Children.Add(img);
                    }
                    else
                    {
                        var txtValue = new TextBox
                                           {
                                               Name = "txt" + propertyInfo.Name,
                                               Height = 23,
                                               Width = 200,
                                               HorizontalAlignment = HorizontalAlignment.Right,
                                               Text = value == null ? String.Empty : value.ToString()
                                           };

                        RegisterName(txtValue.Name, txtValue);
                        StackPanel2.Children.Add(txtValue);

                        var lblEmpty5 = new Label {Height = 10};
                        StackPanel2.Children.Add(lblEmpty5);
                    }
                }
            }

            if (StackPanelImage.Children.Count != 0) return;
            StackPanel1.Margin = new Thickness(10, 10, 0, 0);
            StackPanel2.Margin = new Thickness(10, 10, 10, 0);
        }
    }
}
